<?php

namespace MoChat\App\Statistic\Action\Employee;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 员工跟进分析
 * @Controller
 */
class Index extends AbstractAction
{
    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticEmployee/index", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $data['startTime'] = $data['startTime'] ?? date('Y-m-01 00:00:00');
        $data['endTime'] = $data['endTime'] ?? date('Y-m-d H:i:s');
        $list = Db::table('work_employee as employee')
            ->when(!empty($data['deptName']), function ($query) use ($data) {
                $query->where('dept.name', 'like', '%'.$data['deptName'].'%');
            })
            ->when(!empty($data['employeeName']), function ($query) use ($data) {
                $query->where('employee.name', 'like', '%'.$data['employeeName'].'%');
            })
            ->leftJoin('work_department as dept', 'dept.id', '=', 'employee.main_department_id')
            ->leftJoin('original_client_employee as original_client', 'original_client.work_employee_id', '=', 'employee.id')
            ->leftJoin('client as client', 'client.work_employee_id', '=', 'employee.id')
            ->select([
                'employee.id',
                'employee.name',
                'dept.name as deptName',
                'original_client.client_number as originalClientNumber',//原客户数
                Db::raw('COUNT(mc_client.id) as nowClientNumber'),//现有客户数
            ])
            ->groupBy(['employee.id'])
            ->paginate();
        $list || $list = collect([]);
        $list=$list->toArray();
        if (!empty($list['data'])) {
            $employeeIds = array_column($list['data'], 'id');
            $distributionClients = Db::table('client')
                ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                    $query->where('created_at', '>=', $data['startTime']);
                    $query->where('created_at', '<=', $data['endTime']);
                })
                ->whereIn('work_employee_id', $employeeIds)
                ->select([
                    Db::raw('COUNT(*) as count'),
                    'work_employee_id',
                ])->get();
            $distributionClients = array_column($distributionClients->toArray(), 'count', 'work_employee_id');


            $effectiveVisitNumbers = Db::table('call_record')
                ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                    $query->where('created_time', '>=', $data['startTime']);
                    $query->where('created_time', '<=', $data['endTime']);
                })
                ->whereIn('work_employee_id', $employeeIds)
                ->where('call_duration', '>',0)
                ->select([
                    Db::raw('COUNT(*) as count'),
                    'work_employee_id',
                ])->get();
            $effectiveVisitNumbers = array_column($effectiveVisitNumbers->toArray(), 'count', 'work_employee_id');
            foreach ($list['data'] as &$value) {
                $value->distributionClientNumber = $distributionClients[$value->id]['count'] ?? 0;//分配客户数]
                $value->effectiveVisitNumber = $effectiveVisitNumbers[$value->id]['count'] ?? 0;//有效拜访数]
                $value->visitRate = $value->nowClientNumber ? bcmul(bcdiv((string)$value->effectiveVisitNumber, (string)$value->nowClientNumber, 6), 100, 2) . '%' : '0%';
            }
            unset($value);
            $list['originalClientNumberTotal']=array_sum(array_column($list['data'], 'originalClientNumber'));
            $list['distributionClientNumberTotal']=array_sum(array_column($list['data'], 'distributionClientNumber'));
            $list['nowClientNumberTotal']=array_sum(array_column($list['data'], 'nowClientNumber'));
            $list['effectiveVisitNumberTotal']=array_sum(array_column($list['data'], 'effectiveVisitNumber'));
        }
        return $list;
    }
}
